package Tools;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.ManyToMany;

import models.Actions;
import models.User;

public class CRUD {
	//init iction data
  	public static void init(){
  		//init admin root
  		List<User> ul = User.findAll();
  		if(ul.size() == 0 || ul == null){
  			System.out.println("Iction Data Init >> Admin:root");
  			User u = new User("root", "123456");
  			System.out.println("Iction Data Init >> @author Mr.J.");
  			User Mr_J = new User("Mr.J","123456");
  			u.save();
  			Mr_J.save();
  		}
  		//init admin root menu
  		List<Actions> al = Actions.findAll();
  		if(al.size() == 0 || al == null){
  			System.out.println("Iction Data Init >> Admin:root:Menus");
  			Actions a1 = new Actions("UserAdmin", null, 10, "/UserAdmin/index");
  			Actions a2 = new Actions("ArticleAdmin", null, 9, "/ArticleAdmin/index");
  			Actions a3 = new Actions("AdvertAdmin", null, 8, "/AdvertAdmin/index");
  			Actions a4 = new Actions("PermissionAdmin", null, 7, "/PermissionAdmin/index");
  			al = new ArrayList<Actions>();
  			al.add(a1);al.add(a2);al.add(a3);al.add(a4);
  		}
		User u = User.find("name=?", "root").first();
		if(u != null){
			u.actions = al;
			u.save();
		}
		User Mr_J = User.find("name=?", "Mr.J").first();
		if(Mr_J != null){
			Mr_J.actions = al;
			Mr_J.save();
		}
  		
  	}
  	
  	/** 联机删除多对多关系（中间表）状态测试 **/
  	/**
  	 * @Test(1)>>
  	 * 		User:@ManyToMany(cascade={CascadeType.REMOVE,CascadeType.PERSIST})
  	 * 		Actions:@ManyToMany(mappedBy="actions")
  	 * 结果删除User的同时把Actions表中的信息也一起删除了，而不是只删除中间表的信息。所以CascadeType.REMOVE不能用
  	 * @Test(2)>>
  	 * 		User:@ManyToMany(CascadeType.PERSIST)
  	 * 		Actions:@ManyToMany(mappedBy="actions")
  	 * 结果删除User只删除了中间表，并没有删除Actions，这是我需要的结果。
  	 * **/
  	public static void cascadeRemoveManyToMany(){
  		User root = User.find("name=?", "root").first();
  		if(root != null)
  			root.delete();
  	}
  	/** 联机删除多对多关系（中间表）状态测试 **/
  	public static void cascadeRemoveManyToMany_otherSide(){
  	  	/**
  	  	 * @Test(1)>>
  	  	 * 		User:@ManyToMany(CascadeType.PERSIST)
  	  	 * 		Actions:@ManyToMany(mappedBy="actions")
  	  	 * 结果删除Actions失败，因为中间表的约束
  		/**************************************************************/
//  		List<Actions> acs = Actions.findAll();
//  		for(Actions a : acs) a.delete();
  		/**************************************************************/
  		
  	  	/**
  	  	 * @Test(2)>>
  	  	 * 		User:@ManyToMany(CascadeType.PERSIST)
  	  	 * 		Actions:@ManyToMany(mappedBy="actions")
  	  	 * 结果删除User_Actions中间表成功，因为mappedBy="actions"给了User主控权，所有的业务逻辑均由User支配，所以中间表的删除由
  	  	 * <code>u.actions.clear();</code>控制。这是我要的结果
  	  	 * **/
  		List<Actions> acs = Actions.findAll();
  		for(Actions a : acs) {
  			List<User> users = a.users;
  			for(User u : users) {
  				u.actions.clear();
  				u.save();
  			}
  		}
  	}
}
